package com.yanyeori.framework.core.util;

import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.yanyeori.framework.core.constant.BaseConstant;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码工具类
 *
 * @author chenkuan 2021/4/7
 */
public class QRCodeUtil {

    /**
     * 生成二维码（嵌入图片）
     *
     * @param content      二维码携带文本内容
     * @param qcSize       二维码大小（像素）
     * @param logoFilePath 嵌入图片路径
     * @param logoSize     嵌入图片大小（像素）
     * @param qrPath       二维码图片生成文件
     */
    public static void createQRCode(String content, int qcSize, String logoFilePath, int logoSize, String qrPath) throws Exception {
        //1. 生成二维码图片
        BufferedImage image = QRCodeUtil.createImage(content, qcSize);
        //2. 二维码图片中嵌入logo
        insertImage(image, logoFilePath, logoSize);
        //3. 图片写入磁盘
        ImageIO.write(image, "png", new File(qrPath));
    }

    /**
     * 生成二维码（不包含图片）
     *
     * @param content 二维码携带文本内容
     * @param qcSize  二维码大小（像素）
     * @param qrPath  二维码图片生成文件
     */
    public static void createQRCode(String content, int qcSize, String qrPath) throws Exception {
        //1. 生成二维码图片
        BufferedImage image = QRCodeUtil.createImage(content, qcSize);
        //2. 图片写入磁盘
        ImageIO.write(image, "png", new File(qrPath));
    }

    /**
     * 解析二维码
     *
     * @param file 二维码图片文件
     * @return 二维码携带内容
     */
    public static String parseQRCode(File file) throws Exception {
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Map<DecodeHintType, Object> hints = new HashMap<>();
        hints.put(DecodeHintType.CHARACTER_SET, BaseConstant.UTF_8);
        result = new MultiFormatReader().decode(bitmap, hints);
        return result.getText();
    }

    /**
     * 解析二维码
     *
     * @param path 二维码图片路径
     * @return 二维码携带内容
     */
    public static String parseQRCode(String path) throws Exception {
        return QRCodeUtil.parseQRCode(new File(path));
    }

    /***
     * 生成二维码图片
     *
     * @param content 二维码携带文本内容
     * @param qrSize  二维码图片大小（像素）
     * @return BufferedImage
     */
    private static BufferedImage createImage(String content, int qrSize) throws WriterException {
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, BaseConstant.UTF_8);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, qrSize, qrSize, hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }

    /**
     * 图片中嵌入图片（二维码中插入logo）
     *
     * @param qrBi     二维码BufferedImage
     * @param imgPath  插入图片路径
     * @param logoSize 插入图片大小（像素）
     */
    private static void insertImage(BufferedImage qrBi, String imgPath, int logoSize) throws IOException {
        // 判断嵌入的文件是否存在
        File file = new File(imgPath);
        if (!file.exists()) {
            throw new RuntimeException("The file does not exist");
        }

        // 读取嵌入的图片
        Image imgSource = ImageIO.read(new File(imgPath));
        int width = imgSource.getWidth(null);
        int height = imgSource.getHeight(null);

        // 压缩LOGO
        if (width > logoSize) {
            width = logoSize;
        }
        if (height > logoSize) {
            height = logoSize;
        }
        Image image = imgSource.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.drawImage(image, 0, 0, null); // 绘制缩小后的图
        g.dispose();
        imgSource = image;

        // 插入LOGO
        Graphics2D graph = qrBi.createGraphics();
        int x = (qrBi.getWidth() - width) / 2;
        int y = (qrBi.getHeight() - height) / 2;
        graph.drawImage(imgSource, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    /**
     * 当二维码中嵌入图片时, 需要创建自定义LuminanceSource
     */
    static class BufferedImageLuminanceSource extends LuminanceSource {
        private final BufferedImage image;
        private final int left;
        private final int top;

        BufferedImageLuminanceSource(BufferedImage image) {
            this(image, 0, 0, image.getWidth(), image.getHeight());
        }

        BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {
            super(width, height);

            int sourceWidth = image.getWidth();
            int sourceHeight = image.getHeight();
            if (left + width > sourceWidth || top + height > sourceHeight) {
                throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
            }

            for (int y = top; y < top + height; y++) {
                for (int x = left; x < left + width; x++) {
                    if ((image.getRGB(x, y) & 0xFF000000) == 0) {
                        image.setRGB(x, y, 0xFFFFFFFF); // = white
                    }
                }
            }

            this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);
            this.image.getGraphics().drawImage(image, 0, 0, null);
            this.left = left;
            this.top = top;
        }

        public byte[] getRow(int y, byte[] row) {
            if (y < 0 || y >= getHeight()) {
                throw new IllegalArgumentException("Requested row is outside the image: " + y);
            }
            int width = getWidth();
            if (row == null || row.length < width) {
                row = new byte[width];
            }
            image.getRaster().getDataElements(left, top + y, width, 1, row);
            return row;
        }

        public byte[] getMatrix() {
            int width = getWidth();
            int height = getHeight();
            int area = width * height;
            byte[] matrix = new byte[area];
            image.getRaster().getDataElements(left, top, width, height, matrix);
            return matrix;
        }

        public boolean isCropSupported() {
            return true;
        }

        public LuminanceSource crop(int left, int top, int width, int height) {
            return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
        }

        public boolean isRotateSupported() {
            return true;
        }

        public LuminanceSource rotateCounterClockwise() {
            int sourceWidth = image.getWidth();
            int sourceHeight = image.getHeight();
            AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);
            BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);
            Graphics2D g = rotatedImage.createGraphics();
            g.drawImage(image, transform, null);
            g.dispose();
            int width = getWidth();
            return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);
        }
    }
}
